GOHOSTOS:=$(shell go env GOHOSTOS)
GOPATH:=$(shell go env GOPATH)
VERSION=$(shell git describe --tags --always)


# 跨平台proto文件查找
ifeq ($(GOHOSTOS), windows)
	Git_Bash=$(subst \,/,$(subst cmd\,bin\bash.exe,$(dir $(shell where git))))
	PROTO_FILES=$(shell $(Git_Bash) -c "find protos -name *.proto")
	API_FILES=$(shell $(Git_Bash) -c "find api -name *.api")
else
	PROTO_FILES=$(shell find protos -name "*.proto")
	API_FILES=$(shell find api -name "*.api")
endif

# 路径处理函数
define proto_path
$(1) -> $(2)
endef


.PHONY: proto
proto:
	@echo "🔧 开始生成RPC代码..."
	@for file in $(PROTO_FILES); do \
		# 获取相对路径（去除protos/前缀） \
		rel_path=$$(echo $$file | sed 's|^protos/||'); \
		# 去除.proto扩展名 \
		base=$$(basename $$rel_path .proto); \
		# 构建目标目录（保留原始路径结构） \
		target_dir="./rpc/$$rel_path"; \
		go_target_dir="./protos/"; \
		target_dir=$${target_dir%.proto}; \
		# 创建目标目录 \
		mkdir -p $$target_dir; \
		# 执行代码生成 \
		echo "📄 处理文件: $$file"; \
		goctl rpc protoc $$file \
			--go_out=$$go_target_dir \
			--go-grpc_out=$$go_target_dir \
			--zrpc_out=$$target_dir \
			--client=true \
			-m; \
		if [ $$? -ne 0 ]; then \
			echo "❌ $$file 生成失败"; \
			exit 1; \
		fi; \
	done
	@echo "✅ RPC代码生成完成！"

.PHONY: init
# init env
init:
	go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
	go install github.com/zeromicro/go-zero/tools/goctl@latest
	go install github.com/envoyproxy/protoc-gen-validate@v1.0.2
# 清理规则
clean:
	@echo "🧹 清理生成文件..."
	@find ../rpc -name "*.pb.go" -delete
	@find ../rpc -name "*.pb.grpc.go" -delete
	@find ../rpc -name "*.pb.zrpc.go" -delete

.PHONY: build


.PHONY: api
api:
	@echo "🔧 开始生成API代码..."
	@for file in $(API_FILES); do \
		rel_path=$$(echo $$file | sed 's|^api/||'); \
		base=$$(basename $$rel_path .api); \
		target_dir="./rpc/$$rel_path"; \
		rel_path=${rel_path%.proto}; \
		echo "📁 处理文件: $$file"; \
		mkdir -p "./rpc/$$rel_path"; \
		goctl api go -api $$file \
			--dir=./api/$$base \
			#--proto_path=./api; \
		if [ $$? -ne 0 ]; then \
			echo "❌ $$file 生成失败"; \
			exit 1; \
		fi; \
	done
	@echo "✅ API代码生成完成！"

.PHONY: user
user:
	@echo $(VERSION)
	make proto
	cd rpc/user && mkdir -p ../../bin/ && CGO_ENABLED=0 GOOS=linux \
    GOARCH=amd64 GOPROXY=https://goproxy.cn,direct go build -ldflags "-X main.Version=$(VERSION)" -o  ../../bin/server user.go